package com.wyh.service.serviceImpl.appservieripml;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wyh.common.enums.ResultCodeEnum;
import com.wyh.common.exception.CustomException;
import com.wyh.common.exception.ResourceNotFoundException;
import com.wyh.common.exception.ThreeMeterNotFoundException;
import com.wyh.common.exception.ThreeMeterReadingNotFoundException;
import com.wyh.common.utils.SubStringFourUtils;

import com.wyh.domain.dto.gfive.LoginUser;
import com.wyh.domain.dto.groupfour.threemeterDTO.*;

import com.wyh.domain.po.gfive.User;
import com.wyh.domain.po.gfour.ThreemeterReading4;

import com.wyh.domain.vo.gruopfour.threemeterVO.*;
import com.wyh.mapper.appmapper.ThreemeterMapper;
import com.wyh.service.appservice.ChargeService;
import com.wyh.service.appservice.ThreemeterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import static com.wyh.common.enums.FindResourceEnum.HOUSE_TYPE;
import static com.wyh.common.enums.FindResourceEnum.RENTED;
import static com.wyh.common.enums.ResultCodeEnum.*;

/**
 * @author : 是你
 * @since : 2024/6/4 下午3:58
 */
@Service
@Slf4j
public class ThreemeterServiceImpl implements ThreemeterService {

    @Autowired
    private ThreemeterMapper threemeterMapper;

    @Autowired
    private ChargeService chargeService;

    //     获取SecurityContext中的Authentication对象
    private static User getAdminUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            // 获取用户信息
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            return loginUser.getUser();
        } else {
            throw new CustomException(ResultCodeEnum.USER_NOT_LOGIN);
        }
    }

    /**
     * 获取当前账期
     * 假定账期为每个月的1号
     *
     * @return LocalDate 账期
     */
    private static LocalDate getAccountingPeriod() {
        LocalDate time = LocalDate.now();
        if (time.getDayOfMonth() != 1) {
            time = time.withDayOfMonth(1);
        }
        return time;
    }

    //    @Override
//    public PageResult<ThreeMeterTotalVO> getThreeMeter(GetThreeMeterListDTO getThreeMeterListDTO) {
//        LocalDate time = getAccountingPeriod();
//        List<Integer> resourceIds = chargeService.getAllResourceIds(HOUSE_TYPE.getCode(), RENTED.getCode());
//        if (resourceIds == null || resourceIds.isEmpty()) {
//            throw new ResourceNotFoundException(RESOURCE_NOT_ERROR.getCode(), RESOURCE_NOT_ERROR.getMsg());
//        }
//        PageHelper.startPage(getThreeMeterListDTO.getCurrentPage(), getThreeMeterListDTO.getPageSize());
//        Page<ThreeMeterTotalVO> page = threemeterMapper.getAllThreeMeter(time, getThreeMeterListDTO.getStatus(), resourceIds);
//        page.forEach(meterTotalVO -> meterTotalVO.setReadingschemeid(SubStringFourUtils.subStringAfterNthSlashFromEnd(meterTotalVO.getReadingschemeid(), 1, ',')));
//        log.info("page:{}", page);
//        return new PageResult<>(page.getTotal(), page.getResult());
//    }
    @Override
    public PageResult<ThreeMeterTotalVO> getThreeMeter(GetThreeMeterListDTO getThreeMeterListDTO) {
        Integer userid = getAdminUser().getId();
        LocalDateTime time = LocalDateTime.now();
        LocalDateTime firstDayOfMonth = time.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        List<Integer> resourceIds = chargeService.getAllResourceIds(HOUSE_TYPE.getCode(), RENTED.getCode());
        if (resourceIds == null || resourceIds.isEmpty()) {
            throw new ResourceNotFoundException(RESOURCE_NOT_ERROR.getCode(), RESOURCE_NOT_ERROR.getMsg());
        }
        PageHelper.startPage(getThreeMeterListDTO.getCurrentPage(), getThreeMeterListDTO.getPageSize());
        Page<ThreeMeterTotalVO> page = threemeterMapper.getAllThreeMeters(userid, firstDayOfMonth, getThreeMeterListDTO.getStatus());
        for (int i = 0; i < page.size(); i++) {
            String name = threemeterMapper.getDevelopmentName(page.getResult().get(i).getProjectId());
            page.getResult().get(i).setDevelopment(name);
        }
        log.info("page:{}", page);
        return new PageResult<>(page.getTotal(), page.getResult());

    }


    @Override
    public PageResult<ThreeMeterDetailVO> threeMeter(ThreeMeterDetailDTO threeMeterDetailDTO) {
        // TODO 获取当前账期
        LocalDate time = getAccountingPeriod();
        List<Integer> resourceIds = chargeService.getAllResourceIds(HOUSE_TYPE.getCode(), RENTED.getCode());
        System.out.println(resourceIds);
        if (resourceIds == null || resourceIds.isEmpty()) {
            throw new ResourceNotFoundException(RESOURCE_NOT_ERROR.getCode(), RESOURCE_NOT_ERROR.getMsg());
        }
        PageHelper.startPage(threeMeterDetailDTO.getCurrentPage(), threeMeterDetailDTO.getPageSize());

        Page<ThreeMeterDetailVO> page = threemeterMapper.threeMeter(time, threeMeterDetailDTO.getProjectId(), threeMeterDetailDTO.getStatus(), resourceIds);

        page.forEach(meterDetailVO -> meterDetailVO.setInfoName(SubStringFourUtils.subStringAfterNthSlashFromEnd(meterDetailVO.getInfoName(), 4, '/')));
        log.info("page:{}", page);
        return new PageResult<>(page.getTotal(), page.getResult());

    }

    @Override
    public ThreeMeterDetailVO threeMeterDetail(Integer threemeterid) {
        LocalDate time = getAccountingPeriod();
        ThreeMeterDetailVO meterDetail = threemeterMapper.threeMeterDetail(threemeterid, time);
        if (meterDetail != null) {
            meterDetail.setInfoName(SubStringFourUtils.subStringAfterNthSlashFromEnd(meterDetail.getInfoName(), 4, '/'));
            return meterDetail;
        } else {
            throw new ThreeMeterNotFoundException(THREEMETER_NOT_ERROR.getCode(), THREEMETER_NOT_ERROR.getMsg());
        }
    }

    @Override
    @Transactional
    public int meterreading(MeterreadingDTO meterreadingDTO) {
        // TODO 获取当前所属账期
        LocalDate time = getAccountingPeriod();
        // TODO 获取抄表人id
        Integer userId = getAdminUser().getId();
//        int userId = 1;
        LocalDateTime time1 = LocalDateTime.now();
        LocalDateTime firstDayOfMonth = time1.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        ThreemeterReading4 threemeterReading4 = threemeterMapper.getThreeMeterReading(meterreadingDTO.getMeterid(), time);
        if (threemeterReading4 != null && threemeterReading4.getReading() == 0) {
            // 设置抄表时间
            LocalDate date = meterreadingDTO.getReadingtime();
            LocalDateTime readingtime = date.atTime(0, 0, 0);
            threemeterReading4.setReadingtime(readingtime);
            // 设置抄表人id
            threemeterReading4.setUserid(userId);
            // 设置抄表值
            threemeterReading4.setReading(meterreadingDTO.getReading());
            // 计算用量
            double dosage = 0;
            if (meterreadingDTO.getReading() > threemeterReading4.getPreviousreading() && meterreadingDTO.getReading() != 0) {
                dosage = meterreadingDTO.getReading() - threemeterReading4.getPreviousreading();
            }
            threemeterReading4.setDosage(dosage);
            int rows = threemeterMapper.meterreading(threemeterReading4);
            if (rows > 0) {
                int scheme = threemeterMapper.updateReadingScheme(firstDayOfMonth, meterreadingDTO.getDevelopmentid());
//                System.out.println(scheme+"||||---------------------------------------------------------");
                if (scheme != 0) {
                    return rows;
                } else {
                    throw new CustomException(SYSTEM_ERROR.getCode(), SYSTEM_ERROR.getMsg());
                }
            } else {
                throw new CustomException(SYSTEM_ERROR.getCode(), SYSTEM_ERROR.getMsg());
            }
        } else {
            throw new ThreeMeterReadingNotFoundException(THREEMETERREADING_NOT_ERROR.getCode(), THREEMETERREADING_NOT_ERROR.getMsg());
        }
    }

    @Override
    @Transactional
    public int revokemeterreading(Integer threeMeterReadingId,Integer developmentid,Integer chargingid) {
        Integer userid = getAdminUser().getId();
        LocalDateTime time1 = LocalDateTime.now();
        LocalDateTime firstDayOfMonth = time1.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        ThreemeterReading4 threemeterReading4 = threemeterMapper.findThreeMeterReading(threeMeterReadingId);
        if (threemeterReading4 != null) {
            int rows = threemeterMapper.revokemeterreading(threeMeterReadingId);
            int row1 = threemeterMapper.updateChargingState(chargingid,userid);
            if (rows > 0 && row1 > 0) {
                return threemeterMapper.revokeReadingScheme(firstDayOfMonth,developmentid);
            } else {
                throw new CustomException(SYSTEM_ERROR.getCode(), SYSTEM_ERROR.getMsg());
            }
        } else {
            throw new ThreeMeterReadingNotFoundException(THREEMETERREADING_NOT_ERROR.getCode(), THREEMETERREADING_NOT_ERROR.getMsg());
        }
    }


    @Override
    public PageResult<ThreeMeterDetailVO> like(ThreemeterLikeDTO threemeterLikeDTO) {
        // TODO 获取当前账期
        LocalDate time = getAccountingPeriod();
        List<Integer> resourceIds = chargeService.getAllResourceIds(HOUSE_TYPE.getCode(), RENTED.getCode());
        IntermediateThreeMeterLike meterLike = new IntermediateThreeMeterLike();
        BeanUtils.copyProperties(threemeterLikeDTO, meterLike);
        meterLike.setTime(time);
        meterLike.setResourceIds(resourceIds);
        PageHelper.startPage(threemeterLikeDTO.getCurrentPage(), threemeterLikeDTO.getPageSize());
        System.out.println(meterLike+"------------------------------");
        if (meterLike.getType() == null){
            meterLike.setType(Arrays.asList(0, 1, 2));
        }
        Page<ThreeMeterDetailVO> page = threemeterMapper.like(meterLike);

        page.forEach(meterDetailVO -> meterDetailVO.setInfoName(SubStringFourUtils.subStringAfterNthSlashFromEnd(meterDetailVO.getInfoName(), 4, '/')));
        log.info("page:{}", page);
        return new PageResult<>(page.getTotal(), page.getResult());

    }

    @Override
    public List<Development> screen() {
        // TODO 获取管理员id
//        int userId = 1;
        Integer userId = getAdminUser().getId();
        List<Development> developmentList = threemeterMapper.getDevelopment(userId);
        for (Development development : developmentList) {
            if (development != null) {
                List<Buildings> buildingsList = threemeterMapper.getBuildings(development.getId());
                for (Buildings buildings : buildingsList) {
                    if (buildings != null) {
                        List<Floor> floors = threemeterMapper.getFloors(buildings.getId());
                        for (Floor floor : floors) {
                            if (floor != null) {
                                List<Resource> resources = threemeterMapper.getResource(floor.getId());
                                floor.setResources(resources);
                            }
                        }
                        buildings.setFloors(floors);
                    }
                }
                development.setBuildingUnits(buildingsList);
            }
        }
        return developmentList;
    }

}
